<template>
  <div>
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.back()"
      title="搜索页面"
      placeholder
    ></van-nav-bar>
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      shape="round"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 搜索历史 -->
    <van-cell-group>
      <van-cell v-for="(item, index) in onReplace" :key="index" icon="search">
        <template #title>
          <div v-html="item" @click="$router.push({path:'/searchResult',query:{q:list[index]}})"  ></div>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell title="历史记录" />
    <van-cell-group>
      <van-cell title="单元格">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="clear" />
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group>
      <van-cell title="单元格">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="clear" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '',
      list: [],
      timer: null
    }
  },
  methods: {
    onSearch () {
      this.$router.push({path:'/searchResult',query:{q:this.value}})
    },
    onInput () {
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (this.value.length == 0) {
          this.list = []
          return
        }
        let res = await getSuggestion(this.value)
        // console.log(res);
        this.list = res.data.data.options
      }, 500)
    }
  },
  computed: {
    onReplace () {
      return this.list.map(item => {
        let reg = new RegExp(this.value, 'ig')
        return item.replace(
          reg,
          match => `<span style="color:red">${match}</span>`
        )
      })
    }
  }
}
</script>

<style></style>
